package com.mychoize.app.cricscore;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.XML;


@SuppressWarnings("serial")
public class CricScoreAppServlet extends HttpServlet {
	
	private DataProvider provider;
	private XMLGenerator generator;
	
	public CricScoreAppServlet(){
		provider = new DataProvider();
		generator = new XMLGenerator();
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("application/json");
		//resp.setContentType("text/xml");
		String response = null;
		int size = 0;

		String idStr = (String)req.getParameter("id");
		String versionStr = (String)req.getParameter("v");
		
		if(idStr == null){
			try {
				response = XML.toJSONObject(getMatchList()).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			size = response.length();
		}
		else{
			int id = 0;
			int version = 0;
			try{
				id = Integer.parseInt(idStr);
				version = Integer.parseInt(versionStr);
			}catch(Exception e){}
			if(idStr!=null && id!=0){
				try {
					response = XML.toString(getResponseScore(id, version));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				size = response.length();
			}
		}
			
		if(response != null){
			resp.setContentLength(size);
			resp.getWriter().println(response);
			resp.setHeader("reply-size", size+"");
		}
		
	}
	
	private String getMatchList() {
		List<Match> matches = provider.getMatches();
		return generator.getMatchesXML(matches);
	}

	private String getResponseScore(int id, int version){
		SimpleScore score = provider.getScore(id);
		if(score.getVersion() == version){
			score = new SimpleScore(null, null, id, XMLGenerator.INT_NO_UPDATE);
		}
		return generator.getScoreXML(score);
	}
}